﻿using System;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using MyClaims = CRM.Authorization.Claim;

namespace CRM.Models
{
    [Comment("用户-模块权限")]
    public class UserClaim : IdentityUserClaim<int>
    {
        [Column("oem_id"), Comment("贴牌OEM ID(分区id)"), Required]
        public int OemId { get; set; }

        public string BinaryStr { get; set; }
        public string HexStr { get; set; }
        public string Base64 { get; set; }

        // TODO: mysql不能用
        // The property 'UserClaim.ClaimValue' could not be mapped because it is of type 'string', which is not a supported primitive type or a valid        // entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in        //  'OnModelCreating'.

        // [Column(TypeName = "bigint")]
        //public override string ClaimValue { get; set; }

        public override void InitializeFromClaim(Claim claim)
        {
            base.InitializeFromClaim(claim);
            var mclm = claim as MyClaims;
            if (mclm == null)
            {
                throw new InvalidCastException($"Please User {typeof(MyClaims)} instead {typeof(Claim)}");
            }
            else
            {
                OemId = mclm.OemId;
                BinaryStr = Convert.ToString(mclm.NumberValue, 2);
                HexStr = Convert.ToString(mclm.NumberValue, 16);
                Base64 = Convert.ToBase64String(BitConverter.GetBytes(mclm.NumberValue));
            }
        }
    }
}